/* eslint-env node */

/*
 * This file runs in a Node context (it's NOT transpiled by Babel), so use only
 * the ES6 features that are supported by your Node version. https://node.green/
 */

// Configuration for your app
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js
const _path = require('node:path')
const { loadEnv } = require('vite')
const { configure } = require('quasar/wrappers')
const IconsResolver = require('unplugin-icons/resolver').default

const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i

function resolveApp(relativePath) {
  return _path.resolve(__dirname, `./${relativePath}`)
}

// 首屏（非按需）加载的路由相对（/src/pages/）路径列表
const _syncRouteViewList_ = [
  'login.vue', 'index.vue', 'index/index.vue',
]

const env = loadEnv(null, process.cwd())

for (const key in env) {
  const value = env[key]

  if (/^true$/i.test(value)) {
    env[key] = true
  } else if (/^false$/i.test(value)) {
    env[key] = false
  } else if (/^\d+$/.test(value)) {
    env[key] = Number(value)
  } else if (/^\s*#/i.test(value)) {
    env[key] = ''
  }
}

const needViteInspect = process.argv && process.argv.includes('--vite-inspect')
const publicPath = env.VITE_APP_PUBLICPATH
const distFolder = 'dist'
let distDir = distFolder
let webDir

if (publicPath) {
  const curDistDir = publicPath.match(/\w+/)

  if (curDistDir && curDistDir[0]) {
    webDir = curDistDir[0]
    distDir = `dist/${webDir}`
  }
}

const aimZip = `./${distDir}.zip`
const gzip = env.VITE_BUILD_GZIP
const useLoadingBar = !!env.VITE_APP_LOADINGBAR_COLOR

module.exports = configure((ctx, _s) => {
  return {
    // https://v2.quasar.dev/quasar-cli/prefetch-feature
    // preFetch: true,

    // app boot file (/src/boot)
    // --> boot files are part of "main.js"
    // https://v2.quasar.dev/quasar-cli/boot-files
    boot: [ 'main' ],
    // https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#css
    css: [ 'app.scss' ],
    // https://github.com/quasarframework/quasar/tree/dev/extras
    extras: [
      // 'ionicons-v4',
      // 'mdi-v5',
      // 'fontawesome-v6',
      // 'eva-icons',
      // 'themify',
      // 'line-awesome',
      // 'roboto-font-latin-ext', // this or either 'roboto-font', NEVER both!
      // 'roboto-font', // optional, you are not bound to it
      // 'material-icons', // optional, you are not bound to it
      // 'mdi-v6'
    ],

    // Full list of options: https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#build
    build: {
      target: {
        browser: [
          'es2019', 'edge88', 'firefox78', 'chrome87', 'safari13.1',
        ],
        node: 'node16',
      },

      vueRouterMode: env.VITE_APP_ROUTE_HISTORY_MODE || 'history',
      // available values: 'hash', 'history'
      // vueRouterBase,
      // vueDevtools,
      // vueOptionsAPI: false,

      // rebuildCache: true, // rebuilds Vite/linter/etc cache on startup

      publicPath,
      // analyze: true, // 自定义配置，rollup-plugin-visualizer
      env,
      // rawDefine: {}
      // ignorePublicFolder: true,
      // minify: false,
      // polyfillModulePreload: true,
      distDir,
      // extendViteConf (viteConf) {},
      // viteVuePluginOptions: {},
      vitePlugins: [
        [ 'unocss/vite' ],
        [ 'vite-plugin-mkcert', { source: 'coding', autoUpgrade: true } ],
        [
          'unplugin-auto-import/vite', {
            imports: [
              'vue', 'vue-router', {
                'quasar': [ 'useQuasar', 'useMeta' ],
                'pinia': [ 'storeToRefs' ],
                '@js/injectInterface': [ [ 'allInterfaceMap', '$http' ] ],
              },
            ],
            dts: 'src/auto-import.d.ts',
          },
        ],
        [ 'unplugin-icons/vite' ],
        [
          'unplugin-vue-components/vite', {
            resolvers: [ IconsResolver() ],
            dts: 'src/components.d.ts',
          },
        ],
        [
          'vite-plugin-pages',
          {
            caseSensitive: true,

            // https://github.com/hannoeru/vite-plugin-pages#importmode
            importMode(filepath, _options) {
              const relativePath = filepath.replace(/^\/src\/pages\//, '')

              if (_syncRouteViewList_.includes(relativePath))
                return 'sync'

              return 'async'
            },
          },
        ],

        gzip
          ? [
              'vite-plugin-compression',
              {
                filter: productionGzipExtensions,
                threshold: 10240,
                deleteOriginFile: env.VITE_BUILD_DELETE_ORIGINFILE, // !!!nginx 需保留原文件
              },
            ]
          : null,
        needViteInspect
          ? [ 'vite-plugin-inspect' ]
          : null,
        [
          'rollup-plugin-visualizer',
          {
            gzipSize: gzip,
            brotliSize: true,
            open: true,
          },
        ],
      ],

      extendViteConf(viteConf, { isServer: _isServer, isClient: _isClient }) {
        const alias = {}
        alias['@'] = resolveApp('src')
        alias['@@'] = resolveApp('src/components')
        alias['@js'] = resolveApp('src/common')
        Object.assign(viteConf.resolve.alias, alias)
        viteConf.logLevel = 'warn' // 'info' | 'warn' | 'error' | 'silent'
      },
    },

    // Full list of options: https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#devServer
    devServer: {
      https: true,
      open: true,
      // 配置服务器
      port: env.VITE_DEV_PORT,
      proxy: {
        [env.VITE_APP_DEV_API_BASEURL]: {
          target: env.VITE_APP_APIURL, // API服务器的地址
          secure: false,
          changeOrigin: true,
          headers: {
            referer: env.VITE_APP_APIURL,
          },
          rewrite: (path) => {
            return path.replace(new RegExp(`^${env.VITE_APP_DEV_API_BASEURL}`), '')
          },
          logLevel: 'debug',
        },
      },
    },

    // https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#framework
    framework: {
      iconSet: 'svg-mdi-v6',
      // Quasar icon set
      lang: 'zh-CN',
      // Quasar language pack
      // For special cases outside of where the auto-import strategy can have an impact
      // (like functional components as one of the examples),
      // you can manually specify Quasar components/directives to be available everywhere:
      //
      // components: [],
      // directives: [],

      // Quasar plugins
      plugins: [
        'Meta', 'Dialog', 'AppFullscreen', 'Notify', 'Loading', 'AppVisibility', 'LocalStorage', 'SessionStorage', ...(useLoadingBar
          ? [ 'LoadingBar' ]
          : []),
      ],
      config: {
        screen: {
          bodyClasses: true,
        },

        notify: {
          // https://quasar.dev/quasar-plugins/notify#api--notify
          type: 'info',
          timeout: 1800,
          position: env.VITE_NOTIFY_POSITION || 'top', // top-left top-right bottom-left bottom-right top bottom left right center
        },
        loadingBar: {
          // https://quasar.dev/vue-components/ajax-bar#api--qajaxbar
          color: env.VITE_APP_LOADINGBAR_COLOR || 'primary',
        },
      },

      cssAddon: true,
    },

    // animations: 'all', // --- includes all animations
    // https://v2.quasar.dev/options/animations
    animations: [
      'fadeIn', 'fadeInRight', 'fadeOut', 'fadeOutLeft', 'fadeInLeft', 'fadeOutRight', 'zoomIn', 'zoomOutUp', 'flipInX', 'flipOutX', 'slideInDown', 'slideOutUp',
    ],
    // htmlVariables: {},
    // https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#property-sourcefiles
    // sourceFiles: {
    //   rootComponent: 'src/App.vue',
    //   router: 'src/router/index',
    //   store: 'src/store/index',
    //   registerServiceWorker: 'src-pwa/register-service-worker',
    //   serviceWorker: 'src-pwa/custom-service-worker',
    //   pwaManifestFile: 'src-pwa/manifest.json',
    //   electronMain: 'src-electron/electron-main',
    //   electronPreload: 'src-electron/electron-preload'
    // },
    // https://v2.quasar.dev/quasar-cli/developing-ssr/configuring-ssr
    ssr: {
      // ssrPwaHtmlFilename: 'offline.html', // do NOT use index.html as name!
      // will mess up SSR
      // extendSSRWebserverConf (esbuildConf) {},
      // extendPackageJson (json) {},
      pwa: false,
      // manualStoreHydration: true,
      // manualPostHydrationTrigger: true,
      prodPort: 3000,
      // The default port that the production server should use
      // (gets superseded if process.env.PORT is specified at runtime)
      middlewares: [ 'render', // keep this as last one
      ],
    },

    // https://v2.quasar.dev/quasar-cli/developing-pwa/configuring-pwa
    pwa: {
      workboxMode: 'generateSW',
      // or 'injectManifest'
      injectPwaMetaTags: true,
      swFilename: 'sw.js',
      manifestFilename: 'manifest.json',
      useCredentialsForManifestTag: false,
      // extendGenerateSWOptions (cfg) {}
      // extendInjectManifestOptions (cfg) {},
      // extendManifestJson (json) {}
      // extendPWACustomSWConf (esbuildConf) {}
    },
    // Full list of options: https://v2.quasar.dev/quasar-cli/developing-cordova-apps/configuring-cordova
    cordova: {
      // noIosLegacyBuildFlag: true, // uncomment only if you know what you are doing
    },
    // Full list of options: https://v2.quasar.dev/quasar-cli/developing-capacitor-apps/configuring-capacitor
    capacitor: {
      hideSplashscreen: true,
    },

    // Full list of options: https://v2.quasar.dev/quasar-cli/developing-electron-apps/configuring-electron
    electron: {
      // extendElectronMainConf (esbuildConf)
      // extendElectronPreloadConf (esbuildConf)
      inspectPort: 5858,
      bundler: 'packager',
      // 'packager' or 'builder'
      packager: {
        // https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#options
        // OS X / Mac App Store
        // appBundleId: '',
        // appCategoryType: '',
        // osxSign: '',
        // protocol: 'myapp://path',
        // Windows only
        // win32metadata: { ... }
      },
      builder: {
        // https://www.electron.build/configuration/configuration
        appId: 'frontend-vite',
      },
    },

    // Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-browser-extensions/configuring-bex
    bex: {
      contentScripts: [ 'my-content-script' ],

      // extendBexScriptsConf (esbuildConf) {}
      // extendBexManifestJson (json) {}
    },
  }
})
